package com.getword.mongodao.impl;

import com.getword.domain.Video;
import com.getword.mongodao.VideoOperations;
import com.mongodb.DBObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Example;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.BasicQuery;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.repository.support.PageableExecutionUtils;

import java.util.List;

public class VideoRepositoryImpl implements VideoOperations {
    @Autowired
    private MongoTemplate mongoTemplate;

    @Override
    public Page<Video> findAllPage(Example<Video> example, DBObject fields, Pageable page) {
        Query query = new BasicQuery(null, fields.toString());
        query.addCriteria((new Criteria()).alike(example));
        query.with(page);
//        Query q = (new Query((new Criteria()).alike(example))).with(page);
        List<Video> list = mongoTemplate.find(query, example.getProbeType());
        return PageableExecutionUtils.getPage(list, page, () -> {
            return mongoTemplate.count(query, example.getProbeType());
        });
    }
}
